package se137.hrbust.hlgshopping137.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import se137.hrbust.hlgshopping137.service.FileManager137;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class FileUploadController137 {


    private final FileManager137 fileManager;

        FileUploadController137(FileManager137 fileManager){
            this.fileManager = fileManager;
        }

        @PostMapping("/image")
        public String image(@RequestParam(name = "upload") CommonsMultipartFile file){
            JSONObject json = new JSONObject();
            if(file == null || file.isEmpty()){
                json.put("uploaded",false);
                json.put("url","");
                return json.toString();
            }
            if(StringUtils.isBlank(file.getOriginalFilename()) || !isAllow(file.getOriginalFilename())){
                json.put("uploaded",false);
                json.put("url","");
                return json.toString();
            }
            String url = fileManager.upload(file);
            if(StringUtils.isBlank(url)){
                json.put("uploaded",false);
                json.put("url","");
                return json.toString();
            }else{
                json.put("uploaded",true);
                json.put("url",url);
                return json.toString();
            }
        }

        private boolean isAllow(String fileName){
            String[] allowFiles = {".gif",".png",".jpg",".jpeg",".bpm",".svg"};
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            List<String> suffixList = Arrays.stream(allowFiles).collect(Collectors.toList());
            return suffixList.contains(suffix);
        }
    }

